package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author DCSGO
 * @version 1.0
 * 通过反射创建对象
 */
public class ReflectionConstructorNew {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> userCls = Class.forName("reflection.User");
        //1.通过无参构造器创建对象
        Object o = userCls.newInstance();
        System.out.println(o);
        //User{name='null', password='null'}

        //2.通过 public 的有参构造器创建对象
        Constructor<?> constructor = userCls.getConstructor(String.class);
        Object o1 = constructor.newInstance("王伟");
        System.out.println(o1);
        //User{name='王伟', password='null'}

        //3.通过非 public 的有参构造器创建对象
        Constructor<?> declaredConstructor = userCls.getDeclaredConstructor(String.class, String.class);
        declaredConstructor.setAccessible(true);//爆破 设置该构造器是可使用的
        //对于非 public 修饰的构造器(包括方法) 不进行爆破就会抛出 IllegalAccessException 异常
        Object o2 = declaredConstructor.newInstance("小米", "8888");
        System.out.println(o2);
        //User{name='小米', password='8888'}
    }
}

class User {
    private String name;
    private String password;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    private User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
